package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Report;
import cn.wolfcode.crm.mapper.ReportMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.realm.MyRealm;
import cn.wolfcode.crm.service.IReportService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class ReportServiceImpl implements IReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        reportMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Report selectByPrimaryKey(Long id) {
        return reportMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Report> selectAll() {
        return reportMapper.selectAll();
    }

    @Override
    public void saveOrUpdate(Report entity) {
        int guardId = reportMapper.selectGuardId(entity.getGetguard());
        int carnum = reportMapper.selectCarnum(entity.getCarnumber());
        int date = reportMapper.selectDate(entity.getHappendate());
        Subject subject = SecurityUtils.getSubject();
        Employee principal = (Employee) subject.getPrincipal();
        entity.setEmployee(principal);
        if(guardId==0||carnum==0){
            entity.setState(0L);
        } else if(date==0){
            entity.setState(1L);
        }else{
            entity.setState(2L);
        }
        if (entity.getId() != null){

            reportMapper.updateByPrimaryKey(entity);
        }else {
            reportMapper.insert(entity);
        }
    }

    @Override
    public void changeState(Long id) {
        reportMapper.changeState(id);
    }

    @Override
    public PageResult query(QueryObject qo) {
        int total = reportMapper.query4Count(qo);
        if(total == 0 ){
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Report> rows = reportMapper.query4List(qo);
        return new PageResult(total,rows);
    }
}
